package com.banciyuan.bcywebview.biz.setting;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.UserApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.helper.ActionbarHelper;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.dialog.ConfirmDialog;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.biz.pwd.ChangePwdConfirmPhoneAcitivty;
import com.banciyuan.bcywebview.biz.register.BindPhoneActivity;
import com.banciyuan.bcywebview.biz.register.OldPhoneValidActivity;
import com.banciyuan.bcywebview.utils.constants.MyConstants;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.sns.UsersAPI;
import com.google.gson.Gson;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WbAuthListener;
import com.sina.weibo.sdk.auth.WbConnectErrorMessage;
import com.sina.weibo.sdk.auth.sso.SsoHandler;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.daoexample.model.UserRelevance;

public class UserRelevanceActivity extends BaseActivity implements View.OnClickListener {
    private TextView mPhoneNum;
    private TextView mWeiboName;
    private RequestQueue mQueue;
    private SsoHandler mSsoHandler;
    private UserRelevance userRelevance;
    private static int GO_BINDPHONE = 1000;
    private static int GO_REBINDPHONE = 1001;
    private ActionbarHelper mActionbarHelper;
    private ProgressbarHelper mProgressbarHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.userrelevance_layout);
        initArgs();
        initActionbar();
        initUi();
        initAction();
        initProgressbar();
        initData();
    }

    @Override
    protected void initArgs() {
        mQueue = VolleyQueue.getRquest(this);
        mSsoHandler = new SsoHandler(this);
    }

    @Override
    protected void initActionbar() {
        View mActionBarView = findViewById(R.id.base_action_bar);
        mActionbarHelper = new ActionbarHelper(this, mActionBarView);
        mActionbarHelper.setTitle(getString(R.string.account_relevance));
    }

    @Override
    protected void initUi() {
        mPhoneNum = (TextView) findViewById(R.id.tv_phone_num);
        mWeiboName = (TextView) findViewById(R.id.tv_weibo_name);
    }

    @Override
    protected void initAction() {
        findViewById(R.id.rl_bindphone).setOnClickListener(this);
        findViewById(R.id.rl_bindsina).setOnClickListener(this);
        findViewById(R.id.rl_changepwd).setOnClickListener(this);
    }

    @Override
    protected void initProgressbar() {
        View mProgressbarView = findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                initData();
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initData() {
        String url = HttpUtils.BASE_URL + UserApi.getUserRelevance();
        List<BcyPair> paramsList = new ArrayList<>();
        paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(this).getToken()));
        HashMap<String, String> params = HttpUtils.getData(paramsList);
        Response.Listener succ = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                if (StatusCodeUtils.dealStatusCode(s, UserRelevanceActivity.this)) {
                    try {
                        JSONObject result = new JSONObject(s);
                        Gson gson = new Gson();
                        userRelevance = gson.fromJson(result.getString(HttpUtils.UPLOAD_DATA), UserRelevance.class);
                        processData();
                        mProgressbarHelper.onSuccess();
                    } catch (Exception e) {
                        e.printStackTrace();
                        mProgressbarHelper.onFailed();
                    }
                }
            }
        };

        Response.ErrorListener error = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                mProgressbarHelper.onFailed();
            }
        };
        OnErrorProxy errorProxy = new OnErrorProxy(error, succ, url, this, params);
        StringRequestParam stringRequest = new StringRequestParam(Request.Method.POST, url, params, succ, errorProxy);
        mQueue.add(stringRequest);
    }

    private void processData() {
        if (userRelevance.isBind_mobile()) {
            mPhoneNum.setText(userRelevance.getMobile());
        } else {
            mPhoneNum.setText(getString(R.string.click_to_bind));
        }
        if (userRelevance.isBind_weibo()) {
            mWeiboName.setText(userRelevance.getWeibo());
        } else {
            mWeiboName.setText(getString(R.string.click_to_bind));
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_bindphone:
                if (userRelevance != null && !userRelevance.isBind_mobile()) {
                    Intent intent = new Intent(this, BindPhoneActivity.class);
                    startActivityForResult(intent, GO_BINDPHONE);
                } else {
                    ConfirmDialog.Builder builder = new ConfirmDialog.Builder(this);
                    builder.setDescString(getString(R.string.confirm_change_bind_phone))
                            .setActionString(getString(R.string.change_bind))
                            .setActionClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Intent intent = new Intent(UserRelevanceActivity.this, OldPhoneValidActivity.class);
                                    intent.putExtra(gotoUtil.INTENT_VALUE_ONE, userRelevance.getMobile());
                                    startActivityForResult(intent, GO_REBINDPHONE);
                                }
                            })
                            .setCancelString(getString(R.string.mydialog_cancel))
                            .create().show();
                }
                break;
            case R.id.rl_bindsina:
                if (userRelevance != null && !userRelevance.isBind_weibo())
                    doweiboAuthor();
                break;
            case R.id.rl_changepwd:
                if (userRelevance.isBind_mobile()) {
                    Intent intent = new Intent(this, ChangePwdConfirmPhoneAcitivty.class);
                    startActivityForResult(intent, GO_BINDPHONE);
                } else {
                    MyToast.show(this, getString(R.string.bind_phone_first));
                }
                break;
        }
    }

    private void doweiboAuthor() {
        mSsoHandler.authorize(new WbAuthListener() {
            @Override
            public void onSuccess(Oauth2AccessToken oauth2AccessToken) {
                try {
                    bindSina(oauth2AccessToken);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void cancel() {

            }

            @Override
            public void onFailure(WbConnectErrorMessage wbConnectErrorMessage) {

            }
        });
    }

    private void bindSina(final Oauth2AccessToken accessToken) throws Exception {
        UsersAPI usersAPI = new UsersAPI(this, MyConstants.APP_KEY, accessToken);
        final Long mUid = Long.parseLong(accessToken.getUid());
        usersAPI.getUserInfo(mQueue, String.valueOf(mUid), accessToken.getToken(), new UsersAPI.UserInfoListener() {
            @Override
            public void onError() {
                MyToast.show(UserRelevanceActivity.this, getString(R.string.author_fail));
            }

            @Override
            public void onComplete(String result) {
                try {
                    JSONObject json = new JSONObject(result);
                    String sinaName = json.getString("name");
                    String etime = String.valueOf(accessToken.getExpiresTime() / 1000);
                    String token = accessToken.getToken();
                    bindSinaServer(String.valueOf(mUid), sinaName, etime, token);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void bindSinaServer(String mUid, String name, String etime, String token) {
        List<BcyPair> paramsList = new ArrayList<>();
        String url = HttpUtils.BASE_URL + UserApi.getBindSina();
        paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(this).getToken()));
        paramsList.add(new BcyPair(HttpUtils.SINA_PARAM_UID, mUid));
        paramsList.add(new BcyPair(HttpUtils.SINA_PARAM_TOKEN, token));
        paramsList.add(new BcyPair(HttpUtils.SINA_PARAM_NAME, name));
        paramsList.add(new BcyPair(HttpUtils.SINA_PARAM_ETIME, etime));
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String result) {
                if (StatusCodeUtils.dealStatusCode(result, getContext())) {
                    initData();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
            }
        };
        HashMap<String, String> map = HttpUtils.getData(paramsList);
        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, onError);
        mQueue.add(requestParam);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if ((requestCode == GO_BINDPHONE || requestCode == GO_REBINDPHONE) && resultCode == RESULT_OK) {
            initData();
        } else if (mSsoHandler != null) {
            mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
    }
}
